/**
 * auth: zhukaijun
 * date: 2022-4-10
 * des: oss uploader handler for muti file
 */
class UploadHandler {
    constructor(api) {
        this.ApiHandler = api;
    }

    cancel(index) {
        this.ApiHandler.cancelTask[index].cancel();
    }

    clearCance() {
        this.ApiHandler.cancelTask = {};
    }
    upload(fileList, step, done, parallel) {
        let taskList = [],
            exitsNames = [];
        this.ApiHandler.invoker("ossSign").execute((data) => {
            let info = data.data;
            for (const index in fileList) {
                if (Object.hasOwnProperty.call(fileList, index)) {
                    let item = fileList[index],
                        name = item.name || item.nativeName,
                        keyValue =
                        (process.env.NODE_ENV == 'production' ? 'prod/' : 'test/') + "upload/" + item.type + "/upload_" +
                        Date.now() + "_" + index +
                        "*" +
                        name +
                        (item.type ? "." + item.type : ""),
                        ossData = new FormData(); //创建oss数据对象
                    ossData.append(
                        "name",
                        name + (item.type ? "." + item.type : "")
                    );
                    ossData.append("key", keyValue);
                    ossData.append("policy", info.policy);
                    ossData.append("OSSAccessKeyId", info.accessId);
                    ossData.append("success_action_status", 200);
                    ossData.append("Signature", info.signature);
                    ossData.append("file", item.raw);
                    taskList.push({
                        name: "ossUpload",
                        method: "post",
                        param: ossData,
                        fileName: exitsNames.indexOf(name) > -1 ? name + "(" + index + ")" : name,
                        type: item.type,
                        path: "https://oss.storage.zkj.life/" + keyValue,
                        size: item.raw.size,
                    });
                    exitsNames.push(name);
                }
            }
            if (taskList.length < 1) {
                done([]);
                return;
            }
            this.ApiHandler.invokerList(taskList, parallel)
                .execute((data, index, d) => {
                    step(index);
                }).then((dataList) => {
                    done(taskList);
                });
        }, "get");
        return this;
    }
}

let instance = 0;

export default {
    newInstance(apiHandler, create) {
        if (create || !instance) {
            instance = new UploadHandler(apiHandler);
        }
        return instance;
    }
}